/**   
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-03 22:07:10  
 * Copyright (c) 2015- joysuch-版权所有     
 */

package com.joysuch.wwyt.core.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import com.joysuch.wwyt.core.bean.SimpleSelectListRecursiveBean;
import com.joysuch.wwyt.core.entity.BaseRegion;
import com.joysuch.wwyt.core.repository.BaseRegionDao;
import com.joysuch.wwyt.core.service.BaseRegionService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class BaseRegionServiceImpl implements BaseRegionService {

    @Autowired
    private BaseRegionDao dao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;

    @Override
    public void add(BaseRegion entity) throws Exception {
        dao.save(entity);
    }

    @Override
    public void update(BaseRegion entity) throws Exception {
        BaseRegion content = dao.findById(entity.getId()).get();
        if (content != null) {
            // TODO set nessessary properties
            dao.save(entity);
        }
    }

    @Override
    public Page<BaseRegion> findByPage(Pageable page) {
        return dao.findAll(page);
    }

    @Override
    public void delete(Long id) {
        dao.deleteById(id);
    }

    @Override
    public BaseRegion findById(Long id) {
        return dao.findById(id).get();
    }

    @Override
    public SimpleSelectListRecursiveBean queryTree() {
        List<BaseRegion> all = dao.findAll();
        Map<Long, List<SimpleSelectListRecursiveBean>> parentMap = new HashMap<>();
        List<SimpleSelectListRecursiveBean> allList = new ArrayList<>(all.size());
        for (BaseRegion b : all) {
            SimpleSelectListRecursiveBean bean = convert(b);
            List<SimpleSelectListRecursiveBean> list = parentMap.get(b.getPid());
            if (list == null) {
                list = new ArrayList<SimpleSelectListRecursiveBean>();
                parentMap.put(b.getPid(), list);
            }
            list.add(bean);
            allList.add(bean);
        }
        for (SimpleSelectListRecursiveBean bean : allList) {
            List<SimpleSelectListRecursiveBean> list = parentMap.get(bean.getValue());
            bean.setChildren(list);
        }
        // 根节点
        return parentMap.get(0L).get(0);
    }

    private SimpleSelectListRecursiveBean convert(BaseRegion b) {
        SimpleSelectListRecursiveBean sb = new SimpleSelectListRecursiveBean();
        sb.setLabel(b.getName());
        sb.setValue(b.getId());
        return sb;
    }

}
